package Dao.impl;

import BaseQuery.BaseQuery;
import BaseQuery.CartQuery;
import Bean.Cart;
import Dao.ICartDao;
import Utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartDao implements ICartDao {
	QueryRunner queryRunner;
	public CartDao() {
		queryRunner= JdbcUtils.getQueryRunner();
	}
	@Override
	public int add(Cart cart) throws SQLException {
		//这里Id不用进行添加，自增的
		String sql = "insert into t_cart( foodId, businessId, userId, quantity) VALUES(?,?,?,?)";
		return queryRunner.update(sql,cart.getFoodId(),
				cart.getBusinessId(),
				cart.getUserId(),
				cart.getQuantity());
	}

	@Override
	public int update(Cart cart) throws SQLException {
		String sql = "update t_cart set  foodId=?, businessId=?, userId=?, quantity=? where cartId=?";
		return queryRunner.update(sql,
				cart.getFoodId(),
				cart.getBusinessId(),
				cart.getQuantity(),
				cart.getUserId(),
				cart.getCartId());
	}

	@Override
	public int delete(Integer id) throws SQLException {
		String sql="delete from t_cart where cartId=?";
		return queryRunner.update(sql,id);
	}

	@Override
	public Cart getById(Integer id) throws SQLException {
		String sql="select foodId, businessId, userId, quantity from t_cart where cartId=?";
		return queryRunner.query(sql,new BeanHandler<Cart>(Cart.class),id);
	}

	@Override
	public List<Cart> getAll() throws SQLException {
		String sql="select cartId,foodId, businessId, userId, quantity from t_cart";
		return queryRunner.query(sql,new BeanListHandler<Cart>(Cart.class));
	}

	@Override
	public int getCount(BaseQuery baseQuery) throws SQLException {
		String sql="select count(cartId) from t_cart ";
		List<Object> list=new ArrayList<>();
		return queryRunner.query(sql,new ScalarHandler<Long>(),list.toArray()).intValue();
	}

	@Override
	public List<Cart> getByPage(BaseQuery baseQuery) throws SQLException {
		CartQuery query=(CartQuery) baseQuery;
		System.out.println(query.getCartId());
		List<Object> params=new ArrayList<>();
		String sql="select cartId,foodId, businessId, userId, quantity from t_cart where 1=1";
		if(query.getCartId()!=null&& query.getCartId()!=0) {
			sql+=" and cartId =?";
			params.add(query.getCartId());
		}
		sql+=" ORDER BY cartId DESC limit ?,?";
		params.add(query.getstartIndex());
		params.add(query.getPageCount());
		System.out.println("查询语句："+sql);
		System.out.println("参数集合："+params);
		return queryRunner.query(sql,new BeanListHandler<Cart>(Cart.class),params.toArray());
	}
}
